/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package guiforms;

import BankAuth.ExternalBank;
import controlers.MainControler;
import controlers.PaymentControler;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import model.Customer;

/**
 *
 * @author Tasos
 */
public class PaymentForm extends javax.swing.JDialog {
private float total;  //To poso ths agoras
private List<ExternalBank> bankList; //h lista trapezwn
private PaymentControler pc = new PaymentControler(); //o Payment Controler
private boolean validPayment; //H metavliti egyrhs plhrwmhs
private int paytryes; //o Counter prospathiwn plhrwmhs
private String customerId; //to ID toy pelath
    /**
     * Creates new form PaymentForm
     */
    public PaymentForm() {
        paytryes=0;
        //Modal wste na mpei se hold o Parent BuyProductsScreen, ayto ginetai wste na mporesei na
        //dwthei sthn validPayment h swsth timh prin elegxthei apo to control
        //ths BuyProductsScreen (To vasiko Control einai embeded sthn forma)
        //Quick&Dirty way!!!
        setModal(true);  
        this.bankList=pc.getBanks();
        //h plhrwmh einai akyrh ws otou na theorhthei eggyrh (enoxos ews apodikseos...)
        validPayment = false;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BankPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("BankPU").createEntityManager();
        externalBankQuery = java.beans.Beans.isDesignTime() ? null : BankPUEntityManager.createQuery("SELECT e FROM ExternalBank e");
        externalBankList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : externalBankQuery.getResultList();
        externalBankQuery1 = java.beans.Beans.isDesignTime() ? null : BankPUEntityManager.createQuery("SELECT e FROM ExternalBank e");
        externalBankList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : externalBankQuery1.getResultList();
        jTextFAmount = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextFieldCardNumber = new javax.swing.JTextField();
        jTextFieldName = new javax.swing.JTextField();
        jTextFieldCVV = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btnPay = new javax.swing.JButton();
        jTextFieldSurname = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jComboBoxBanks = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();

        jTextFAmount.setEditable(false);
        jTextFAmount.setText("0");

        jLabel1.setText("Ποσο");

        jTextField1.setEditable(false);
        jTextField1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jTextField1.setText("ΠΛΗΡΩΜΗ ΜΕ ΠΙΣΤΩΤΙΚΗ ΚΑΡΤΑ");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jTextFieldCardNumber.setText("Card Number");
        jTextFieldCardNumber.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCardNumberActionPerformed(evt);
            }
        });

        jTextFieldName.setText("Name");

        jTextFieldCVV.setText("CVV");
        jTextFieldCVV.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCVVActionPerformed(evt);
            }
        });

        jLabel2.setText("Αρ. Κάρτας");

        jLabel3.setText("Όνομα Κατόχου");

        jLabel4.setText("Αρ. Αφαλείας");

        btnPay.setText("ΠΛΗΡΩΜΗ");
        btnPay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPayActionPerformed(evt);
            }
        });

        jTextFieldSurname.setText("Surname");

        jLabel5.setText("Επώνυμο Κατόχου");

        jComboBoxBanks.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1" }));
        jComboBoxBanks.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxBanksActionPerformed(evt);
            }
        });

        jLabel6.setText("Τράπεζα");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(20, 20, 20)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3)))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jLabel5)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(jLabel4)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextFieldCVV, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jTextFieldSurname)
                    .addComponent(jTextFieldName)
                    .addComponent(jTextFieldCardNumber)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextFAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBoxBanks, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(142, 142, 142)
                        .addComponent(btnPay))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(75, 75, 75)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(62, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBoxBanks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldCardNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldCVV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addComponent(btnPay)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jTextFieldCardNumberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCardNumberActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldCardNumberActionPerformed

    private void jTextFieldCVVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCVVActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldCVVActionPerformed

    private void jComboBoxBanksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxBanksActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBoxBanksActionPerformed

    //Even Handler Plhrwmhs
    private void btnPayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPayActionPerformed
    //An exei dwthei card Number
    if(jTextFieldCardNumber.getText() != null){
    //xrhsimopoioume ton paymentControler gia na paroume ta stoixeia toy idiokthth ths pistwtikhs [provlhma asfaleias edw???]
    ArrayList<String> credentials = pc.getCredentials(jTextFieldCardNumber.getText());
    ExternalBank bk1 = (ExternalBank)jComboBoxBanks.getSelectedItem();
    //an ta stoixeia pou parelifthisan yparxoun kai einai ta idia me ayta pou exoun dwthei sth forma
    if(credentials.size()>0 && credentials.get(0).equals(jTextFieldName.getText().toUpperCase() + " " + jTextFieldSurname.getText().toUpperCase()) &&
    credentials.get(1).equals(jTextFieldCVV.getText()) && credentials.get(2).equals(bk1.getBankId().toString())){
    //tote validpayment true kai idopoihsh toy pelath
    validPayment=true;  
    JOptionPane.showMessageDialog(this, "Η πληρωμή ολοκληρώθηκε με επιτυχία");
    this.setVisible(false);
    }
    else //alliws idopoihsh pelath kai meiwsh prospathiwn kata 1
    JOptionPane.showMessageDialog(this, "Σφάλμα κατα την επιβεβαίωση των στοιχέιων");       
    paytryes++;
    if(paytryes>=3) 
        this.setVisible(false);
    }
    }//GEN-LAST:event_btnPayActionPerformed
    
    
    
    //public method seter gia enhmerwsh ths formas gia ton pelath
    public void setCustomer(String custid)
    {
    customerId = custid;    
    }
    
   //public method seter gia enhmerwsh ths formas gia to poso
    public void setTotal(float total){
    this.total=total;
    jTextFAmount.setText(""+total);
    }
   
    //public method getter gia to validation ths plhrwmhs
   public boolean validation(){
    return validPayment;
   }
   
   
   //public method gia na parei aytomath h forma ta stoixeia toy pelath
   //apo to profile kai thn lista twn trapezwn
   public void updateFields() {
       //xrhsh MainControler 
       MainControler mc = new MainControler();
       //instanciate ena pelath me to ID toy
       Customer tempcust = mc.findCustomerByCard(customerId);
       //an ta stoixeia/pelaths vrethikan 
       if (tempcust!= null && tempcust.getCreditcard()!= null)
        {
        //enhmerwsh twn pediwn ths formas
        jTextFieldCardNumber.setText(tempcust.getCreditcard());
        jTextFieldName.setText(tempcust.getFirstName());
        jTextFieldSurname.setText(tempcust.getLastName());
        }
        //enhervsh jComboBox epiloghs trapezwn
        jComboBoxBanks.removeAllItems();
        for (ExternalBank bank : bankList){
        jComboBoxBanks.addItem(bank);
        }
    }
   
   
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PaymentForm().setVisible(true);
            }
        });
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager BankPUEntityManager;
    private javax.swing.JButton btnPay;
    private java.util.List<BankAuth.ExternalBank> externalBankList;
    private java.util.List<BankAuth.ExternalBank> externalBankList1;
    private javax.persistence.Query externalBankQuery;
    private javax.persistence.Query externalBankQuery1;
    private javax.swing.JComboBox jComboBoxBanks;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextFAmount;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextFieldCVV;
    private javax.swing.JTextField jTextFieldCardNumber;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldSurname;
    // End of variables declaration//GEN-END:variables

    

}
